package com.weipai.demo.controller;

import com.weipai.demo.enums.RetCode;
import com.weipai.demo.mapper.PayOrderMapper;
import com.weipai.demo.model.PayOrder;
import com.weipai.demo.util.Response;
import com.weipai.demo.util.WxPayUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Map;

import static github.wxpay.sdk.WXPayUtil.xmlToMap;

@RestController
@RequestMapping("/wxPay")
public class WxPayController {

    @Autowired
    private PayOrderMapper payOrderMapper;
    /**
     * 微信扫码支付 调用微信api统一下单接口:
     */
    @RequestMapping("/createOrder")
    public Response createQRCode(HttpServletRequest request, HttpServletResponse response,
                                 @Param("phone") String phone) throws Exception {
        Response response1 = new Response();
        if (phone.isEmpty())
        {
            response1.setCode(RetCode.PAY_FAILD);
            return response1;
        }
        PayOrder pay = new PayOrder();
        pay.setMobile(phone);
        PayOrder payOrder = payOrderMapper.selectOne(pay);
       return WxPayUtil.createQRCode(request,response,payOrder);
    }

    /**
     * 微信回调函数
     * 支付成功后微信服务器会调用此方法，修改数据库订单状态
     */
    @RequestMapping(value = "/wxPayCallBack.do")
    public String wxPayCallBack(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("回调成功");
        try {
            InputStream inStream = request.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            outSteam.close();
            inStream.close();
            String result = new String(outSteam.toByteArray(), "utf-8");// 获取微信调用我们notify_url的返回信息
            Map<String, String> map = xmlToMap(result);
            if (map.get("result_code").equalsIgnoreCase("SUCCESS")) {
                //返回成功后修改订单状态
                String out_trade_no = map.get("out_trade_no");
//                this.proOrdersService.updateByOrderId(out_trade_no);
            }
        } catch (Exception e) {

        }
        return "SUCCESS";
    }



}
